import { HsAdminInput, HsAdminTable } from '@hs-admin/base-components'
import { Button, Modal, Popconfirm, Popover, Select } from 'antd'
import { commonExportColumns, exportStatus, exportTypes, HsAdminSelectDataItem } from '@hs-admin/components'
import { initPageType, message, usePageChange } from '@hs-admin/utils'
import { approveExport, exportList, exportToLocal, rejectExport } from '@/api/export'
import { useCallback, useEffect, useRef, useState } from 'react'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10,
  morePageOptions: true
}

const columns = (call: (id: string) => void, callRest: () => void) => [
  {
    title: '导出标识名称',
    key: 'name',
    dataIndex: 'name'
  },
  {
    title: '导出人',
    key: 'person',
    dataIndex: 'person',
    render: (_, row: any) => `${row.user?.name ?? '--'}(${row.user?.email ?? '--'})`
  },
  ...commonExportColumns('申请时间'),
  {
    title: '操作',
    key: 'option',
    dataIndex: 'option',
    render: (_, row: any) => (
      <div className="flex gap-4 items-center">
        <Button
          type="link"
          onClick={() => {
            exportToLocal(row.id).then(() => {
              message.success('导出成功')
            })
          }}>
          查看导出
        </Button>
        <>
          {row.status === 'wait_for_audit' ? (
            <Popconfirm
              title="是否通过审批？"
              cancelText="驳回"
              cancelButtonProps={{
                danger: true
              }}
              okText="通过"
              onCancel={() => {
                call(row.id)
              }}
              onConfirm={() => {
                approveExport(row.id).then(() => {
                  message.success('通过成功')
                  callRest()
                })
              }}>
              <Button type="link">审批</Button>
            </Popconfirm>
          ) : row.status === 'rejected' ? (
            <Popover content={row.reject_msg} title="驳回原因" trigger="click">
              <Button type="link">驳回原因</Button>
            </Popover>
          ) : null}
        </>
      </div>
    )
  }
]

const Atlas = () => {
  const [dataList, setDataList] = useState<Array<any>>([])
  const tempKeywords = useRef('')
  const [keywords, setKeywords] = useState('')
  const [type, setType] = useState('')
  const [status, setStatus] = useState('')

  const [release_item_id, setReleaseItemId] = useState('')

  const [open, setOpen] = useState(false)

  const [msg, setMsg] = useState('')

  const tempItem = useRef({
    id: ''
  })

  const request = useCallback(
    async (page: number, pageSize: number) => {
      const res = await exportList({
        page,
        page_size: pageSize,
        type: type || undefined,
        status: status || undefined,
        keywords: keywords || undefined,
        release_item_id: release_item_id || undefined,
        view_all: true
      })
      setDataList(res.items)

      return res.total
    },
    [keywords, release_item_id, status, type]
  )

  const { pagination, resetPageAndTriggerRequest } = usePageChange(initPage, request)

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  const openModal = (id: string) => {
    setOpen(true)
    tempItem.current = {
      id
    }
    setMsg('')
  }

  return (
    <>
      <div className="flex gap-12 items-center">
        <div className="flex gap-4 items-center">
          <HsAdminInput
            className="flex-1"
            placeholder="请输入搜索内容"
            onChange={(e: any) => {
              tempKeywords.current = e.target.value
            }}
          />
          <Button
            type="primary"
            onClick={() => {
              setKeywords(tempKeywords.current)
            }}>
            搜索
          </Button>
        </div>
        <div className="flex items-center gap-4">
          <span>导出类型</span>
          <Select
            className="flex-1 min-w-32"
            placeholder="请选择"
            value={type}
            onChange={(value) => {
              setType(value)
            }}
            options={exportTypes}
          />
        </div>
        <div className="flex items-center gap-4">
          <span>关联数据库</span>
          <HsAdminSelectDataItem
            value={release_item_id}
            className="flex-1 min-w-32 max-w64"
            placeholder="请选择"
            onChange={(value: string) => {
              setReleaseItemId(value)
            }}
          />
        </div>
        <div className="flex items-center gap-4">
          <span>审批状态</span>
          <Select
            className="flex-1"
            placeholder="请选择"
            value={status}
            onChange={(value) => {
              setStatus(value)
            }}
            options={exportStatus}
          />
        </div>
      </div>
      <div className="flex-1 overflow-auto flex flex-col gap-4">
        <HsAdminTable
          className="flex-1"
          dataSource={dataList}
          columns={columns(openModal, resetPageAndTriggerRequest)}
          pagination={pagination}
          rowKey={(record: any) => record.id}
        />
      </div>
      <Modal
        width="50vw"
        open={open}
        title="驳回原因"
        onCancel={() => {
          setOpen(false)
        }}
        onOk={() => {
          rejectExport(tempItem.current.id, {
            message: msg
          }).then(() => {
            tempItem.current = {
              id: ''
            }
            message.success('驳回成功')
            setOpen(false)
            resetPageAndTriggerRequest()
          })
        }}>
        <div className="flex items-center gap-2 py-4">
          <span className="whitespace-nowrap">驳回原因：</span>
          <HsAdminInput
            value={msg}
            TextArea={true}
            onChange={(e: any) => {
              setMsg(e.currentTarget.value)
            }}
          />
        </div>
      </Modal>
    </>
  )
}

export default Atlas
